package com.bupt.ilink.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bupt.ilink.entity.Studyspace.*;
import com.bupt.ilink.entity.Studyspace.DTO.SortOrderUpdateDTO;
import com.bupt.ilink.mapper.*;
import com.bupt.ilink.service.StudyCourseFileService;
import com.bupt.ilink.service.StudyWebSourseService;
import com.bupt.ilink.service.studyaboutTeacherCourse.FileSourceHandleThreadService;
//import com.bupt.ilink.service.studyaboutTeacherCourse.handleFileSource;
//import com.bupt.ilink.service.studyaboutTeacherCourse.uploadFileSource;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.bupt.ilink.controller.LearningPlaza.File.FileHandleController;
import com.bupt.ilink.entity.FileTranscriptionTaskResponse;
import com.bupt.ilink.entity.Studyspace.DTO.CourseResponse;
import com.bupt.ilink.entity.Studyspace.DTO.StudyCourseFileResponse;
import com.bupt.ilink.entity.Studyspace.DTO.StudySourceFileResponse;
import com.bupt.ilink.entity.User;
import com.bupt.ilink.service.OssService;
import com.bupt.ilink.service.StudyaboutTeacherService;
import com.bupt.ilink.service.bailian.FileService;
import com.bupt.ilink.utils.SnowflakeIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import com.bupt.ilink.utils.R;

import java.util.*;

import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
@RequestMapping("/StudySpaceTeacher")
public class StudyaboutTeacherController {
    @Autowired
    private OssService ossService;
    @Autowired
    private FileService fileService;
    @Autowired
    private FileSourceHandleThreadService fileSourceHandleThreadService;

    @Autowired
    private CourseSourceMapper courseSourceMapper;

    @Autowired
    private StudyFileSourceMapper studyFileSourceMapper;

    @Autowired
    private StudyWebSourseService studyWebSourseService;

    @Autowired
    private StudyWebSourseMapper studyWebSourseMapper;

    @Autowired
    private StudyCourseFileMapper studyCourseFileMapper;
    @Autowired
    private StudyaboutTeacherService studyaboutTeacherService;
    @Autowired
    private FileHandleController fileHandleController;
    @Autowired
    private FileTranscriptionController fileTranscriptionController;
    @Autowired
    private FileTranscriptionMapper fileTranscriptionMapper;

    @Autowired
    private StudyCourseFileService studyCourseFileService;

    /**
     * 更新文件排序顺序
     * @param dto 包含父目录 ID 和排序后的文件 ID 列表
     * @return 操作结果
     */
    @PostMapping("/update-sort-order")
    public ResponseEntity<?> updateSortOrder(@RequestBody SortOrderUpdateDTO dto) {
        try {
            studyCourseFileService.updateSortOrder(dto);
            return ResponseEntity.ok("排序更新成功");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            // 记录日志（省略）
            return ResponseEntity.status(500).body("排序更新失败");
        }
    }


    /*
    编写人：张博
    用途：创建课程
    备注：courseJson是课程信息，files是相关图片
     */

    //新建课程
    @PostMapping("/createCourse")
    public R createCourse(@AuthenticationPrincipal UserDetails userDetails,
                          @RequestParam("course") String courseJson,
                          @RequestParam("files") List<MultipartFile> files){
        try{
            // 解析 JSON 数据
            ObjectMapper objectMapper = new ObjectMapper();
            CourseResponse course = objectMapper.readValue(courseJson, CourseResponse.class);

            User user = (User) userDetails;
            boolean result = studyaboutTeacherService.createCourseWithFolder(
                    user.getUserId(),course, files);
            if (result) {
                return R.ok("课程创建成功");
            } else {
                return R.failure("课程创建失败");
            }
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }


    /*
    编写人：张博
    用途：修改课程信息
    备注：courseJson是课程信息，files是相关图片
     */
    @PostMapping("/modify_course")
    public R modifyCourse(@AuthenticationPrincipal UserDetails userDetails,
                          @RequestParam("courseId") Long courseId,
                          @RequestParam("course") String courseJson,
                          @RequestParam("files") List<MultipartFile> files){
        try{
            // 解析 JSON 数据
            ObjectMapper objectMapper = new ObjectMapper();
            CourseResponse course = objectMapper.readValue(courseJson, CourseResponse.class);

            User user = (User) userDetails;
            boolean result = studyaboutTeacherService.updateCourseById(
                    user.getUserId(), courseId, course, files);
            if (result) {
                return R.ok("课程修改成功");
            } else {
                return R.failure("课程修改成功");
            }
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }

    //删除课程文件，删除课程记录和所有的课程资源
    @GetMapping("/deleteFiles")
    public R deleteFiles( @RequestParam Long courseFileId,@RequestParam Long courseId) {
//        User user = (User) userDetails;
        try {
//            boolean result = studyaboutTeacherService.deleteCoursefile(courseFileId,courseId);
            boolean result = studyaboutTeacherService.deleteCoursefileBycourseFile(courseFileId,courseId);
            if (result) {
                return R.ok("课程文件及其资源删除成功");
            } else {
                return R.failure("课程文件及其资源删除失败");
                         }
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.failure(e.getMessage());
//            throw new RuntimeException(e);
        }

    }


    //删除课程资源
    @GetMapping("/deleteSources")
    public R deleteSources( @RequestParam Long source_id,@RequestParam String type) {
        try {
            boolean result = studyaboutTeacherService.deleteSourcesfile(source_id, type);
            if (result) {
                return R.ok("课程资源删除成功");
            } else {
                return R.failure("课程资源删除失败");
            }
        } catch (Exception e) {
            // 可以根据异常类型或消息，返回一个合适的错误响应
            return R.failure("课程资源删除时发生错误：" + e.getMessage());
        }
////        User user = (User) userDetails;
//        boolean result = studyaboutTeacherService.deleteSourcesfile(source_id,type);
//        if (result) {
//            return R.ok("课程资源删除成功");
//        } else {
//            return R.failure("课程资源删除失败");
//        }
    }


    // 查看所有课程，返回json格式的层级文件树,增加了按照sortOrder排序
    @GetMapping("/getallCourese")
    public ResponseEntity<StudyCourseFileResponse> getAllCourses(@AuthenticationPrincipal UserDetails userDetails,
                                                                 @RequestParam Long courseFileId) {
//        User user = (User) userDetails;
        StudyCourseFileResponse courseResourceTree = new StudyCourseFileResponse();
        courseResourceTree.setCourseFileId(courseFileId);
        courseResourceTree.setChildFiles(studyaboutTeacherService.getCourseFiles(courseFileId, null));  // 传入 null 表示不过滤
        return ResponseEntity.ok(courseResourceTree);
    }


    /*//查看所有课程，返回json格式的层级文件树
    @GetMapping("/getallCourese")
    public ResponseEntity<StudyCourseFileResponse> getAllCourses(@AuthenticationPrincipal UserDetails userDetails,
                                                                       @RequestParam Long courseId) {
        User user = (User) userDetails;
        StudyCourseFileResponse courseResourceTree = studyaboutTeacherService.getCourseTree(user.getUserId(), courseId);
        return ResponseEntity.ok(courseResourceTree);
    }*/
    //获取文件夹下对应资源
    @GetMapping("/getCourseFileSources")
    public R getCourseFileSources(@RequestParam Long courseFileId) {
        List<StudySourceFileResponse> SourceFiles = studyaboutTeacherService.getSourseFiles(courseFileId,"");
        List<StudyWebSourse> webSourse = studyWebSourseMapper.getWebByCourseFileId(courseFileId);
        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("studySourceFiles", SourceFiles);
        responseMap.put("studyWebSourse", webSourse);
        return R.ok(responseMap);
    }


    //根据文件夹ID给出子文件夹和资源
    @GetMapping("/getCourseFile")
    public R getCourseFile(@RequestParam Long courseFileId,@RequestParam String type,@RequestParam(required = false, defaultValue = "") String sentence) {
        Map<String, Object> responseMap = new HashMap<>();
        if (type.equals("folder")){
            List<StudyCourseFileResponse> courseFiles = studyaboutTeacherService.getCourseFiles(courseFileId,sentence);
            responseMap.put("studyCourseFiles", courseFiles);
        }
        if (type.equals("Source")){
            List<StudySourceFileResponse> SourceFiles = studyaboutTeacherService.getSourseFiles(courseFileId,sentence);
            List<StudyWebSourse> webSourse = studyWebSourseMapper.getWebByCourseFileId(courseFileId);
            //依据sentence对 List<StudyWebSourse>中的Name进行过滤
            if (sentence != null && !sentence.isEmpty()) {
                webSourse = webSourse.stream()
                        .filter(response -> response.getWebName().contains(sentence))
                        .toList();
            }
            responseMap.put("studyWebSourse", webSourse);
            responseMap.put("studySourceFiles", SourceFiles);
        }
        return R.ok(responseMap);
    }
    //获取所有上传文件的状态
    @GetMapping("/getAllSourcesState")
    public R getAllSourcesState(@AuthenticationPrincipal UserDetails userDetails,@RequestParam(required = false, defaultValue = "") String sentence) {
        User user = (User) userDetails;
        List<StudySourceFileResponse> SourceFiles = studyaboutTeacherService.getSourseFilesALL(user.getUserId(),sentence);
        return R.ok("获取所有资源成功", SourceFiles);
    }

    //根据用户ID给出对应课程列表
    @GetMapping("/getCourse")
    public ResponseEntity<List<StudyCourseFileResponse>> getCourse(@AuthenticationPrincipal UserDetails userDetails,@RequestParam(required = false, defaultValue = "") String sentence) {
        User user = (User) userDetails;
        List<StudyCourseFileResponse> courseResourceTree = studyaboutTeacherService.getUserCourseByuserId(user.getUserId(),sentence);
        return ResponseEntity.ok(courseResourceTree);
    }
    //修改文件夹命名
    @PostMapping("/updateCourseFileName")
    public R updateCourseFileName(@RequestParam Long courseFileId, @RequestParam String newFileName,@RequestParam String type) {
        // 创建一个 UpdateWrapper 对象
        if (type.equals("文件夹")){
            UpdateWrapper<StudyCourseFile> updateWrapper = new UpdateWrapper<>();
            // 设置要更新的列和值
            updateWrapper.set("name",newFileName);
            // 通过条件指定要更新的行，例如根据 id 更新
            updateWrapper.eq("courseFile_id", courseFileId);
            // 执行更新操作
            studyCourseFileMapper.update(null, updateWrapper);

        } else if (type.equals("音视频")) {
            UpdateWrapper<CourseSource> updateWrapper = new UpdateWrapper<>();
            // 设置要更新的列和值
            updateWrapper.set("file_name",newFileName);
            // 通过条件指定要更新的行，例如根据 id 更新
            updateWrapper.eq("coursesource_id", courseFileId);
            // 执行更新操作
            courseSourceMapper.update(null, updateWrapper);
        }else if (type.equals("文档")){
            UpdateWrapper<StudyFileSource> updateWrapper = new UpdateWrapper<>();
            // 设置要更新的列和值
            updateWrapper.set("file_name",newFileName);
//            updateWrapper.set("")
            // 通过条件指定要更新的行，例如根据 id 更新
            updateWrapper.eq("filesource_id", courseFileId);
            // 执行更新操作
            studyFileSourceMapper.update(null, updateWrapper);
        } else if (type.equals("网页")) {
            StudyWebSourse webSourse = studyWebSourseMapper.selectById(courseFileId);
            if(webSourse != null){
                webSourse.setWebName(newFileName);
                webSourse.setUploadedAt(new Date());
                studyWebSourseMapper.updateById(webSourse);
                return R.ok("修改网页名称成功");
            }
            return R.failure("未找到该网页资源");
        } else {
            return R.failure("类型错误");
        }
        return R.ok("修改成功");

    }


    //给出coursesource_id查询音视频转写结果
    @GetMapping("/getSourceTransResult")
    public R getSourceFile(@RequestParam Long courseSourceId) {
        FileTranscriptionTaskResponse fileTranscriptionTaskResponse =  courseSourceMapper.selectTransResultById(courseSourceId);
        if (fileTranscriptionTaskResponse == null) {
            return R.failure("课程转写资源不存在");
        }
        return R.ok(fileTranscriptionTaskResponse);
    }


//    //根据level层级和courseId给出下层的文件夹
//    @GetMapping("/getCourseFiles")
//    public ResponseEntity<List<StudyCourseFileResponse>> getCourseFiles(@RequestParam Long courseFileId) {
//        List<StudyCourseFileResponse> courseFiles = studyaboutTeacherService.getCourseFiles(courseFileId);
//        return ResponseEntity.ok(courseFiles);
//    }
//
//    //根据当前文件夹ID给出上层的文件夹
//    @GetMapping("/getCourseFileParent")
//    public ResponseEntity<StudyCourseFileResponse> getCourseFileParent(@RequestParam Long courseFileId) {
//        StudyCourseFileResponse courseFileParent = studyaboutTeacherService.getCourseFileParent(courseFileId);
//        return ResponseEntity.ok(courseFileParent);
//    }



    //新建章节
    @PostMapping("/createChapter")//上层文件夹的ID
    public R createChapter(@RequestParam String file_name,@RequestParam Long courseFile_id){
//        User user = (User) userDetails;
        try {
            boolean result = studyaboutTeacherService.createChapter(file_name,courseFile_id);
            if (result) {
                return R.ok("章节创建成功");
            } else {
                return R.failure("章节创建失败");
            }
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }



    }

    @PostMapping("/newcreateChapter")
    public R createChapter(@RequestParam String file_name,
                           @RequestParam Long courseFile_id,
                           @RequestParam Integer sort_order) {
        try {
            boolean result = studyaboutTeacherService.newcreateChapter(file_name, courseFile_id, sort_order);
            if (result) {
                return R.ok("章节创建成功");
            } else {
                return R.failure("章节创建失败");
            }
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }
    //上传OSS
    //上传音视频资源
//    public MultipartFile renameMultipartFile(MultipartFile file, String newFilename) throws IOException {
//        // 获取文件扩展名
//        String originalFilename = file.getOriginalFilename();
//        String fileExtension = "";
//        if (originalFilename != null && originalFilename.contains(".")) {
//            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
//        }
//
//        // 生成新文件名
//        String newFileNameWithExtension = newFilename + fileExtension;
//
//        // 将文件保存到临时文件
//        Path tempFile = Files.createTempFile(null, fileExtension);
//        file.transferTo(tempFile.toFile());
//
//        // 将临时文件重新包装成MultipartFile
//        MultipartFile renamedFile = new MockMultipartFile(
//                newFileNameWithExtension,
//                newFileNameWithExtension,
//                file.getContentType(),
//                new FileInputStream(tempFile.toFile())
//        );
//
//        // 删除临时文件
//        Files.deleteIfExists(tempFile);
//
//        return renamedFile;
//    }

    @PostMapping("/uploadSourceOSS")
    public R uploadSource(
            @RequestParam("file") MultipartFile file,
            @RequestParam("courseFileId") Long courseFileId,
            @RequestParam("language") String language,
            @RequestParam("isTranslated") Boolean isTranslated,
            @RequestParam("speakerType") String speakerType,
            @RequestParam("courseId") Long courseid) {
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();

        // 获取文件扩展名
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }else {
            return R.failure("文件解析扩展名出现错误："+originalFilename);
        }
        // 生成新文件名，使用雪花算法生成的ID
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
        Long id = idGenerator.nextId();
        String newFilename = id+ fileExtension;
        // 获取对应的文件路径，用于关联和存储上传
        StudyCourseFile studyCourseFile = studyCourseFileMapper.selectById(courseFileId);
        if (studyCourseFile == null) {
            return R.failure("文件夹ID无效");
        }
        String filePath = studyCourseFile.getFilePath();
        CourseSource courseSource = new CourseSource();
        courseSource.setCourseSourceId(id);
        courseSource.setLanguage(language);
        courseSource.setIsTranslated(isTranslated);
        courseSource.setSpeakerType(speakerType);
        courseSource.setFileId(courseFileId);
        courseSource.setFileName(file.getOriginalFilename());
        courseSource.setCourseId(courseid);
//        courseSource.setTaskId();
        // 构建并保存资源信息到数据库
        courseSource.setFilesourcePath(filePath+newFilename);
        courseSourceMapper.insert(courseSource);

        //OSS上传
        if (ossService.uploadFile(file, filePath,newFilename)) {
//            successFiles.add(file.getOriginalFilename());

//            return R.ok("文件上传成功: " + file.getOriginalFilename());
            courseSource.setOssWriteStatus(true);
            courseSourceMapper.updateById(courseSource);
            return R.ok("音视频导入成功，OSS文件上传成功: " + file.getOriginalFilename(),courseSource);
        }
        else {
            return R.failure("OSS文件上传失败: " + file.getOriginalFilename());
        }
    }


    //加工音视频视频
    @PostMapping("/handleVideoSource")
    public R handleVideoSource(
            @RequestParam("courseSourceId") Long courseSourceId) {

        CourseSource courseSource = courseSourceMapper.selectById(courseSourceId);
        String fileUrl = ossService.getFileUrl(courseSource.getFilesourcePath());
        if(fileUrl == null){
            return R.failure("文件未找到"+courseSource.getFileName());
        }
        //异步轮询更新
        studyaboutTeacherService.checkVideoStatusAsync(courseSourceId);
        return studyaboutTeacherService.handlefileTrans(courseSource,fileUrl);
        //调用转写api
//        RestTemplate restTemplate = new RestTemplate();
//        MultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<>();
//        requestMap.add("fileUrl", fileUrl);
//        //上传文件并加工
//        ResponseEntity<R> responseEntity = restTemplate.postForEntity("http://localhost:8080/fileTrans/createTask", requestMap, R.class);
//        R response = responseEntity.getBody();
//        if (response == null || response.getCode()==0) {
//            if (response != null) {
//                return R.failure("文件加工转写失败: " + courseSource.getFileName()+" "+response.getMsg());
//            }else {
//                return R.failure("文件加工转写失败: " + courseSource.getFileName());
//            }
//        }else {
//            courseSource.setTranscriptionComplete(true);
//            courseSourceMapper.updateById(courseSource);
//            return R.ok("文件加工转写成功: " +  courseSource.getFileName(),response);
//        }
    }
    //确认音视频加工状态
    @PostMapping("/Jugehandlevideostate")
    public R Jugehandlevideostate(
            @RequestParam("taskId") String taskId) {
//        FileTranscriptionTaskResponse result =fileTranscriptionMapper.selectById(taskId);
//        String sourcePath=result.getOutput_mp3_path();
        CourseSource courseSource = courseSourceMapper.selectOne(new QueryWrapper<CourseSource>().eq("task_id", taskId));

        R result =fileTranscriptionController.getResult(taskId,courseSource.getFilesourcePath());//.substring(0,courseSource.getFilesourcePath().lastIndexOf("/"))
        if (result.getCode()==1 ) {
            FileTranscriptionTaskResponse data = (FileTranscriptionTaskResponse) result.getData();
            if (data.getTaskStatus().equals("COMPLETED")){
                courseSource.setTranscriptionComplete(true);
                courseSourceMapper.updateById(courseSource);
        }
        }
        return result;

    }
    //音视频上传与加工-并发（最终接口）
    @PostMapping("/handlevideoSource_thread")
    public R handlevideoSourceThread(
            @RequestParam("file") MultipartFile file,
            @RequestParam("courseFileId") Long courseFileId,
            @RequestParam("language") String language,
            @RequestParam("isTranslated") Boolean isTranslated,
            @RequestParam("speakerType") String speakerType,
            @RequestParam("courseId") Long courseid)  {
        return fileSourceHandleThreadService.uploadSourceTask(file, courseFileId,language,isTranslated,speakerType,courseid);

    }


    //上传文档资源-任务队列-并发
//    @PostMapping("/uploadfile_sourceOSS_thread")
//    public R uploadfile_sourceOSS_thread(
//            @RequestParam("file") MultipartFile file,
//            @RequestParam("courseFileId") Long courseFileId,
//            @RequestParam("courseId") Long courseid) {
//        // 调用 FileUploadService 处理文件上传任务
//        uploadFileSource uploadFileSource =new uploadFileSource(ossService,studyFileSourceMapper,studyCourseFileMapper,10,15,60,50);
//        return uploadFileSource.uploadFileTask(file, courseFileId,courseid);
//    }

    //文档上传与加工-并发（最终接口）
    @PostMapping("/handlefileSource_thread")
    public R handlefileSourceThread(
            @RequestParam("file") MultipartFile file,
            @RequestParam("courseFileId") Long courseFileId,
            @RequestParam("courseId") Long courseid) {
        // 调用 FileUploadService 处理文件上传任务
        if (file.isEmpty()) {
            log.error("课程："+courseid+"上传的"+courseFileId+"文件为空");
            return R.failure("课程："+courseid+"上传的"+courseFileId+"文件为空");
        }
        return fileSourceHandleThreadService.uploadFileTask(file, courseFileId,courseid);
    }


    @PostMapping("/uploadfileSourceOSS")
    public R uploadfileSource(
            @RequestParam("file") MultipartFile file,
            @RequestParam("courseFileId") Long courseFileId,
            @RequestParam("courseId") Long courseid) {
        try {
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();

            // 获取文件扩展名
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }else {
                return R.failure("文件解析扩展名出现错误："+originalFilename);
            }
            // 生成新文件名，使用雪花算法生成的ID
            SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
            Long id = idGenerator.nextId();
            String newFilename = id+ fileExtension;

            // 获取对应的文件路径，用于关联和存储上传
            StudyCourseFile studyCourseFile = studyCourseFileMapper.selectById(courseFileId);
            if (studyCourseFile == null) {
                return R.failure("文件夹ID无效");
            }
            String filePath = studyCourseFile.getFilePath();
            // 构建并保存资源信息到数据库
            StudyFileSource courseSource = new StudyFileSource();
            courseSource.setFilesourceId(id);
            courseSource.setFileName(file.getOriginalFilename());
            courseSource.setFileId(courseFileId);
            courseSource.setCourseId(courseid);
            courseSource.setFilesourcePath(filePath+newFilename);
            studyFileSourceMapper.insert(courseSource);

            if (ossService.uploadFile(file, filePath,newFilename)) {
//            successFiles.add(file.getOriginalFilename());
                courseSource.setOssWriteStatus(true);
                studyFileSourceMapper.updateById(courseSource);
                return R.ok("文件上传成功: " + file.getOriginalFilename(),courseSource);
            } else {
                return R.failure("文件上传失败: " + file.getOriginalFilename());
//            failedFiles.add(file.getOriginalFilename());
            }
        }
        catch (Exception e) {
            return R.failure("文件上传失败: " + file.getOriginalFilename());
        }


    }
    //加工文档资源-并发
//    @PostMapping("/handlefileSource_thread")
//    public R handlefileSource_thread(
//            @RequestParam("fileSourceId") Long fileSourceId,
//            @RequestParam("file") MultipartFile file
//    )
//    {
//        handleFileSource handleFileSource =new handleFileSource(ossService,studyFileSourceMapper,studyCourseFileMapper,10,15,60,50);
//        return handleFileSource.handleFileTask(file, fileSourceId);
//
//    }

    //加工文档资源：听悟
    @PostMapping("/handlefileSource")
    public R handlefileSource(
            @RequestParam("fileSourceId") Long fileSourceId,@RequestParam("file") MultipartFile file) throws Exception {

        StudyFileSource fileSource = studyFileSourceMapper.selectById(fileSourceId);
        String fileUrl = ossService.getFileUrl(fileSource.getFilesourcePath());
        if(fileUrl == null){
            return R.failure("文件未找到"+fileSource.getFileName());
        }
        //RAG上传加工
        // 找到最后一个斜杠的位置
        int lastSlashIndex = fileSource.getFilesourcePath().lastIndexOf('/');

        // 使用最后一个斜杠位置分割字符串
        String filePath = fileSource.getFilesourcePath().substring(0, lastSlashIndex);
        String newFilename = fileSource.getFilesourcePath().substring(lastSlashIndex + 1);
        R response=fileService.uploadFile(file, filePath,newFilename);
        if (response == null || response.getCode()==0) {
            if (response != null) {
                fileSource.setHandleCompleteStatus(true);
                studyFileSourceMapper.updateById(fileSource);
                return R.failure("RAG文件上传失败: " + fileSource.getFileName()+" "+response.getMsg());
            }else {
                fileSource.setHandleCompleteStatus(true);
                studyFileSourceMapper.updateById(fileSource);
                return R.failure("RAG文件上传失败: " + fileSource.getFileName());
            }
        }else {
            fileSource.setRagCompleteStatus(true);
            studyFileSourceMapper.updateById(fileSource);

        }
        //调用听悟api
        response = fileHandleController.uploadFileFromUrl(fileUrl, fileSource.getFilesourceId());
        if (response == null || response.getCode()==0) {
            if (response != null) {
                fileSource.setHandleCompleteStatus(true);
                studyFileSourceMapper.updateById(fileSource);
                return R.failure("文件加工失败: " + fileSource.getFileName()+" "+response.getMsg());
            }else {
                fileSource.setHandleCompleteStatus(true);
                studyFileSourceMapper.updateById(fileSource);
                return R.failure("文件加工失败: " + fileSource.getFileName());
            }
        }else {
            fileSource.setSmartTextStatus(true);
            fileSource.setHandleCompleteStatus(true);
            studyFileSourceMapper.updateById(fileSource);
            return R.ok("文件加工转写成功: " +  fileSource.getFileName(),response);
        }

    }






}
